package civicinity.ist.psu.edu.rssfeed;

import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.R.drawable;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.databases.CivicinityDatabase;
import civicinity.ist.psu.edu.utils.CivicinityHelpers;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class RSSFeedServiceReceiver extends BroadcastReceiver{
	
	private SharedPreferences mPref;
	private int mResultCount = 0;
	private CivicinityDatabase mDB;
	private RSSFeed[] mFeed = null;
	private ArrayList<RSSDBItem> mArr = null;
	private Context mContext;
	
	/**
	 * When the receiver operated, check if there is any internet connection,
	 * if so, start searching.
	 * if not, just return.
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i("K", "RSSFeed onReceive()");
		
		mContext = context;
		
		// check if there is an internet connection
		if(isNetworkAvailable(context)) {
			
			// check if the screen is on or off
			// if off, start searching.
			//if(!isScreenOn()) {
				mDB = new CivicinityDatabase(context);
		        
		        mArr = new ArrayList<RSSDBItem>();
		        mArr = mDB.getFeeds();
		        
		        // create RSSFeed array
		        mFeed = new RSSFeed[mArr.size()];
				
		        Log.i("K", "Start RSSFeed Search, data is stored in RSSContentsTemp.");
		        
				new getFeedThread().execute();
			//}
		}
		else {
			Log.i("K", "there is no internet connection. can't proceed to search.");
		}
	}
	
	 /**
     * Retrieving the RSS as a AsyncTask
     * @author kyunghan
     *
     */
	private class getFeedThread extends AsyncTask<Void, Void, Void> {
		
		private int getGlobalRSSNum;
		
		@Override
	    protected void onPreExecute() {
	        // connect to the DB helper
			mPref = mPref = PreferenceManager.getDefaultSharedPreferences(mContext);
			getGlobalRSSNum = mPref.getInt("rss_global", 1);
			Log.i("K", "current global value : " + getGlobalRSSNum);
		}

	    /** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
		@Override
	    protected Void doInBackground(Void... Void) {
	    	
			RSSFeedHandler feedHandler = new RSSFeedHandler();

			for(int i = 0 ; i < mArr.size() ; i++) {
				// only search rss when each time is arrived.
				if(getGlobalRSSNum % mArr.get(i).getInterval() == 0) {
					mFeed[i] = feedHandler.getFeed(mArr.get(i).getRSSUrl());
				}
				else {
					mFeed[i] = null;
				}
			}
			return null;
	    }
	    
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    @Override
	    protected void onPostExecute(Void unused) {
	    	
	    	//ArrayList<RSSItem> arr = new ArrayList<RSSItem>();
	    	CivicinityHelpers cHelper = new CivicinityHelpers();
	    	
	    	try {
	    		for(int i = 0 ; i < mArr.size() ; i++) {
		    		
	    			if(mFeed[i] != null) {
	    				Log.i("K", "Feed(" + i + ") is updated.");
	    				if(mFeed[i].getAllItems().size() != 0) {
	    					ArrayList<RSSItem> arr = new ArrayList<RSSItem>();
	    					
		    				for(int j = 0 ; j < mFeed[i].getAllItems().size() ; j++) {
				    			RSSItem item = new RSSItem();
				    			item.setRSSID(i+1);
				    			item.setTitle(mFeed[i].getItem(j).getTitle());
				    			item.setCategory(mFeed[i].getItem(j).getCategory());
				    			item.setDescription(mFeed[i].getItem(j).getDescription());
				    			item.setPubDate(cHelper.convertDateFormatRSS(mFeed[i].getItem(j).getPubDate().trim()));
				    			item.setLink(mFeed[i].getItem(j).getLink().trim());
				    			
				    			arr.add(item);
				    			// send RSSItem and RSSID
				    		}
		    				
		    				mDB.setRSSContents(arr, Constants.TEMP_RSSContents);
		    			}
	    			}
	    			else {
	    				Log.i("K", "Feed(" + i + ") has null value. not being searched.");
	    			}
		    	}
		    	
	    		// insert data into RSSContentsTemp
	    		// and after done, transfer data to RSSContents
		    	//mDB.setRSSContents(arr, Constants.TEMP_RSSContents);

	    		// update the value
	    		SharedPreferences.Editor editor = mPref.edit();
				editor.putInt("rss_global", getGlobalRSSNum + 1);
	    		editor.commit();
	    		
	    		if(mPref.getBoolean("notification_on", true)) {
			    	// show notification for the updated news.
			    	NotificationManager notificationMgr = (NotificationManager)mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
			    	Notification noti = new Notification(R.drawable.civicinity_logo, "[Civicinity] News updated", System.currentTimeMillis());
					noti.flags |= Notification.FLAG_AUTO_CANCEL;

					PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, RSSReader.class), PendingIntent.FLAG_CANCEL_CURRENT);
					noti.setLatestEventInfo(mContext, "Civicinity", "[Civicinity] News updated", contentIntent);
					notificationMgr.notify(820713, noti);
	    		}		    	
	    	}
	    	catch(Exception e) {
	    		Log.i("K", "Exception");
	    	}
	    }
	}
	
	private boolean isNetworkAvailable(Context context) {
		ConnectivityManager cManager = 
			(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		
		NetworkInfo nInfo = cManager.getActiveNetworkInfo();
		
		if(nInfo == null) {
			return false;
		}
		
		Log.i("K", "info : " + nInfo.isConnectedOrConnecting());
		
		return nInfo.isConnectedOrConnecting();
	}
	
	private boolean isScreenOn() {
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		
		boolean isScreenOn = pm.isScreenOn();
		
		return isScreenOn;
	}

	private PowerManager getSystemService(String powerService) {
		// TODO Auto-generated method stub
		return null;
	}
}